package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class TokenFiler implements Filter {

    //1.获取请求的路径,判断是否是登录页面,获取请求头中的token,判断是否为空并且校验token是否符合合法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (uri.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer id = claims.get("id",Integer.class);
            CurrentUserHoler.setCurrentUser(id);
        }catch (Exception e){
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);

        CurrentUserHoler.removeCurrentUser();
    }
}
